<?php
class UserMessage extends Zend_Db_Table_Abstract {
	
	const MESSAGE_ID = "message_id";
	const TARGET_USER_ID = "target_user_id";
	const STATUS = "status";
	
	protected $_primary = "id";
	protected $_name = "user_message";
	
	protected $_referenceMap = array (
    'TargetUser' => array (
        'columns' => 'target_user_id', 
        'refTableClass' => 'User', 
        'refColumns' => 'id' 
    ),
    'Message' => array (
        'columns' => 'message_id', 
        'refTableClass' => 'Message', 
        'refColumns' => 'id' 
    )
    );
    
    /**
     * Find user message by id.
     * 
     * @param $id
     * @return return user message
     */
    public function findById($id) {
    	return $this->find($id)->current();
    }
    
    /**
     * Add new user message.
     * 
     * @param $message
     * @param $targetUser
     * @param $subject
     * @param $type
     * @param $created
     */
    public function addUserMessage($data) {
    	return $this->insert($data);
    }
    
    /**
     * Return message.
     * 
     * @param $userMessage
     */
    public static function getMessage($userMessage) {
    	return $userMessage->findParentRow('Message');
    }
    
    /**
     * Return target user of message.
     * 
     * @param $userMessage
     */
    public static function getTargetUser($userMessage) {
        return $userMessage->findParentRow('User', 'TargetUser');
    }

    /**
     * Update user message status, only update those sender is not equal to the loggedInUser.
     * 
     * @param $userMessageId
     * @param $messageCreatorId
     * @param $messageTargetUserId
     * @param $loggedInUser
     */
    public static function updateUserMessagesStatus($userMessageId, $messageCreatorId, $messageTargetUserId, $loggedInUser) {
    	$table = new UserMessage();
        $userMessage = $table->findById($userMessageId);
        if ($messageCreatorId != $loggedInUser->id 
            || ($messageCreatorId == $messageTargetUserId && $messageCreatorId == $loggedInUser->id)) {
        	$userMessage->status = UserMessageStatus::READ;
        	$userMessage->save();
        }
    }
}
?>